/*
 * search test in dictionary 
 *
 * ZhihuiJin <zhihuijin@gmail.com>
 * vim: ts=4 sw=4 sts=4 et tw=78:
 * Thu Feb  8 13:28:03 JST 2007
 */ 

import org.apache.lucene.document.Document;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Hits;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.Directory;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.analysis.WhitespaceAnalyzer;
import org.apache.lucene.analysis.Analyzer;
import java.io.File;


public class TestSearcher {
	public static void main(String[] args) throws Exception {
		if (args.length != 2) {
			throw new Exception("Usage: " + TestSearcher.class.getName() + " <index dir> <query>");
		}

		File indexDir = new File(args[0]);
		String q = args[1];

		if (!indexDir.exists() || !indexDir.isDirectory()) {
			throw new Exception(indexDir + " is does not exist or is not a directory.");
		}


		search(indexDir, q);
	}

	public static void search(File indexDir, String q)  throws Exception{
		Directory fsDir = FSDirectory.getDirectory(indexDir, false);
		IndexSearcher is = new IndexSearcher(fsDir);
		Analyzer analyzer = new WhitespaceAnalyzer();
        QueryParser parser = new QueryParser("word", analyzer);
		Query query = parser.parse(q);
		Hits hits = is.search(query);

		for (int i = 0; i < 10 && i < hits.length(); i++) {	//output top 10
			Document doc = hits.doc(i);
			String wordInfo = "";
			wordInfo += "word : " + doc.get("word") + "\n";
			//wordInfo += "char : " + doc.get("char") + "\n";
            wordInfo += "dictReading :" + doc.get("dictReading") + "\n";
            wordInfo += "dictMeaning :" + doc.get("dictMeaning") + "\n";
			System.out.println(wordInfo);
		}

		System.out.println("................................................................");
		System.out.println("Found " + hits.length() + " document(s) that matched query '" + q + "':");
	}
}
